<template>
  <div class="agents-container">
    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <div style="display: flex; justify-content: space-between; align-items: center; gap: 20px;">
        <div style="display: flex; gap: 20px; flex: 1;">
          <el-input
            v-model="searchForm.search"
            placeholder="搜索智能体名称或描述"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            style="width: 200px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="searchForm.agent_type"
            placeholder="选择类型"
            clearable
            @change="handleSearch"
            style="width: 120px;"
          >
            <el-option
              v-for="type in agentTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
          
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            @change="handleSearch"
            style="width: 120px;"
          >
            <el-option
              v-for="status in agentStatuses"
              :key="status"
              :label="getStatusLabel(status)"
              :value="status"
            />
          </el-select>
          
          <el-select
            v-model="searchForm.department_id"
            placeholder="选择部门"
            clearable
            @change="handleSearch"
            style="width: 120px;"
          >
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
          
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
        
        <div>
          <el-button type="success" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            创建智能体
          </el-button>
        </div>
      </div>
    </div>

    <!-- 智能体卡片列表 -->
    <div class="agents-grid" v-loading="loading">
      <div
        v-for="agent in agents"
        :key="agent.id"
        class="agent-card"
        @click="viewAgentDetail(agent)"
      >
        <div class="card-header">
          <div class="agent-info">
            <div class="agent-avatar" :title="`Avatar: ${agent.avatar || '无图标'}`">
              <!-- 始终显示默认图标作为背景 -->
              <el-icon size="24" class="default-icon">
                <component :is="getAgentIcon(agent.agent_type)" />
              </el-icon>
              
              <!-- 如果有avatar，在上层显示图片 -->
              <img 
                v-if="getSafeAvatarUrl(agent)" 
                :src="getSafeAvatarUrl(agent)" 
                :alt="agent.name"
                class="avatar-image"
                @error="handleImageError($event, agent)"
                @load="handleImageLoad"
                crossorigin="anonymous"
              />
            </div>
            <div class="agent-basic">
              <h3 class="agent-name">{{ agent.name }}</h3>
              <span class="agent-type">{{ agent.agent_type }}</span>
              <span class="agent-category" v-if="agent.category">{{ agent.category }}</span>
            </div>
          </div>
          <div class="card-actions" @click.stop>
            <el-dropdown @command="handleCommand">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="`edit-${agent.id}`">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="`copy-${agent.id}`">
                    <el-icon><CopyDocument /></el-icon>
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item :command="`delete-${agent.id}`" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item :command="`hard-delete-${agent.id}`" v-if="agent.status === 'deleted'">
                    <el-icon><Delete /></el-icon>
                    永久删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="card-content">
          <p class="agent-description">
            {{ agent.description || '暂无描述' }}
          </p>
          
          <div class="agent-meta">
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>{{ agent.created_by_name || '未知' }}</span>
            </div>
            <div class="meta-item" v-if="agent.department_name">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ agent.department_name }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(agent.created_at) }}</span>
            </div>
          </div>
        </div>
        
        <div class="card-footer">
          <el-tag
            :type="getStatusType(agent.status)"
            size="small"
          >
            {{ getStatusLabel(agent.status) }}
          </el-tag>
          
          <div class="model-info" v-if="agent.config && agent.config.model">
            <el-icon><Cpu /></el-icon>
            {{ agent.config.model }}
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[12, 24, 48, 96]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="!loading && agents.length === 0"
      description="暂无智能体数据"
      :image-size="200"
    >
      <el-button type="primary" @click="showCreateDialog = true">
        创建第一个智能体
      </el-button>
    </el-empty>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingAgent ? '编辑智能体' : '创建智能体'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="agentFormRef"
        :model="agentForm"
        :rules="agentFormRules"
        label-width="100px"
      >
        <el-form-item label="智能体名称" prop="name">
          <el-input
            v-model="agentForm.name"
            placeholder="请输入智能体名称"
            maxlength="64"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="智能体类型" prop="agent_type">
          <el-select
            v-model="agentForm.agent_type"
            placeholder="请选择智能体类型"
            style="width: 100%"
          >
            <el-option
              v-for="type in agentTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="智能体分类" prop="category">
          <el-input
            v-model="agentForm.category"
            placeholder="请输入智能体分类"
            maxlength="64"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="图标" prop="avatar">
          <div class="avatar-uploader">
            <div class="avatar-preview" v-if="agentForm.avatar">
              <img :src="agentForm.avatar" alt="图标预览" class="avatar-image" />
              <div class="avatar-actions">
                <el-button type="danger" size="small" circle @click.stop="removeAvatar">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <el-upload
              v-if="!agentForm.avatar"
              class="avatar-upload"
              action="/api/v1/upload/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
            >
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                上传图标
              </el-button>
              <div class="el-upload__tip">
                只能上传JPG/PNG图片，且不超过2MB
              </div>
            </el-upload>
            <el-input
              v-model="agentForm.avatar"
              placeholder="或输入图标URL"
              maxlength="500"
              class="avatar-input"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="版本号" prop="version">
          <el-input
            v-model="agentForm.version"
            placeholder="请输入版本号"
            maxlength="16"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="agentForm.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="status in agentStatuses"
              :key="status"
              :label="getStatusLabel(status)"
              :value="status"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属部门" prop="department_id">
          <div class="agent-dept-selector">
            <el-tooltip 
              :content="agentForm.department_path || '请选择部门'" 
              placement="top"
              :disabled="!agentForm.department_path || agentForm.department_path.length <= 25"
            >
              <el-input 
                v-model="agentForm.department_path" 
                placeholder="请选择部门" 
                readonly
                @click="showAgentDeptTree = true"
                suffix-icon="ArrowDown"
              >
                <template #append>
                  <el-button 
                    v-if="agentForm.department_id" 
                    @click.stop="clearAgentDepartmentSelection" 
                    icon="Close"
                  />
                </template>
              </el-input>
            </el-tooltip>
            
            <div v-if="showAgentDeptTree" class="agent-tree-dropdown">
              <div class="tree-search">
                <el-input 
                  v-model="agentDeptSearchText" 
                  placeholder="搜索部门" 
                  clearable
                  prefix-icon="Search"
                  @input="filterAgentDeptTree"
                />
              </div>
              <div class="agent-tree-container">
                <el-scrollbar height="250px">
                  <el-tree
                    ref="agentDeptTreeRef"
                    :data="departmentTree"
                    :props="agentDeptTreeProps"
                    :filter-node-method="filterAgentDeptNode"
                    node-key="dept_id"
                    highlight-current
                    :current-node-key="agentForm.department_id"
                    @node-click="handleAgentDeptNodeClick"
                    :expand-on-click-node="false"
                    :check-strictly="true"
                  >
                    <template #default="{ node, data }">
                      <span class="compact-tree-node">
                        <span :class="{'selected-dept': agentForm.department_id === data.dept_id}">
                          {{ data.dept_name }}
                        </span>
                      </span>
                    </template>
                  </el-tree>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="agentForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入智能体描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="模型配置" prop="config">
          <div class="config-header">
            <div class="config-tabs">
              <el-radio-group v-model="configViewMode" size="small">
                <el-radio-button label="json">JSON格式</el-radio-button>
                <el-radio-button label="form">表单格式</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          
          <!-- JSON编辑模式 -->
          <div v-if="configViewMode === 'json'" class="config-form-mode">
            <div class="json-editor-container">
              <el-input
                v-model="configText"
                type="textarea"
                :rows="6"
                placeholder="请输入JSON格式的配置信息"
                :class="{ 'is-error': !validateJsonConfig() && configText.trim() !== '' }"
                style="width: 100%;"
              />
              <div v-if="!validateJsonConfig() && configText.trim() !== ''" class="el-form-item__error">
                JSON格式不正确
              </div>
            </div>
          </div>
          
          <!-- 表单编辑模式 -->
          <div v-else class="config-form-mode">
            <div v-for="(item, index) in configFormItems" :key="`config-item-${index}`" class="config-form-item">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-input 
                    v-model="item.key" 
                    placeholder="键名" 
                    @input="updateConfigFromForm"
                  />
                </el-col>
                <el-col :span="12">
                  <el-input 
                    v-model="item.value" 
                    placeholder="值" 
                    @input="updateConfigFromForm"
                  />
                </el-col>
                <el-col :span="4" style="display: flex; justify-content: space-between;">
                  <el-button 
                    type="danger" 
                    circle 
                    size="small"
                    @click="removeConfigItem(index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <div class="config-form-actions">
              <el-button type="primary" size="small" @click="addConfigItem">
                <el-icon><Plus /></el-icon>
                添加配置项
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ editingAgent ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 智能体详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="智能体详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentAgent" class="agent-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="智能体名称">{{ currentAgent.name }}</el-descriptions-item>
          <el-descriptions-item label="智能体类型">{{ currentAgent.agent_type }}</el-descriptions-item>
          <el-descriptions-item label="智能体分类">{{ currentAgent.category || '未分类' }}</el-descriptions-item>
          <el-descriptions-item label="图标" v-if="currentAgent.avatar">
            <img :src="currentAgent.avatar" alt="图标" style="width: 48px; height: 48px; border-radius: 8px;" />
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentAgent.status)">
              {{ getStatusLabel(currentAgent.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="版本号">{{ currentAgent.version || '1.0.0' }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ currentAgent.description || '暂无描述' }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ currentAgent.created_by_name || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ currentAgent.department_name || '未指定' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentAgent.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(currentAgent.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="配置信息">
            <pre class="json-config">{{ currentAgent.config ? JSON.stringify(currentAgent.config, null, 2) : '{}' }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button type="primary" @click="editAgent(currentAgent.id)">编辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Edit,
  Delete,
  MoreFilled,
  User,
  OfficeBuilding,
  Calendar,
  Cpu,
  CopyDocument,
  ChatDotRound,
  Link,
  Collection,
  Connection,
  DataAnalysis,
  MagicStick
} from '@element-plus/icons-vue'
import {
  getAgentList,
  createAgent,
  updateAgent,
  deleteAgent,
  hardDeleteAgent,
  searchAgents,
  getUserAgentsCount,
  getAgentTypes,
  getAgentCategories,
  getAgentStatuses,
  copyAgent
} from '@/api/agent'
import { getDepartmentTree } from '@/api/department'
import { formatDateTime } from '@/utils/format'
import { debounce } from 'lodash-es'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const agents = ref([])
const total = ref(0)
const agentTypes = ref([])
const agentCategories = ref([])
const agentStatuses = ref([])
const showCreateDialog = ref(false)
const editingAgent = ref(null)
const agentFormRef = ref(null)
const uploadHeaders = ref({})

// 详情对话框状态
const showDetailDialog = ref(false)
const currentAgent = ref(null)

// 搜索表单
const searchForm = reactive({
  search: '',
  agent_type: '',
  category: '',
  status: '',
  department_id: ''
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 12
})

// 智能体表单
const agentForm = reactive({
  name: '',
  description: '',
  avatar: '',
  category: '',
  agent_type: '',
  status: 'active',
  department_id: '',
  version: '1.0.0',
  config: null
})

// 部门选项
const departmentOptions = ref([])
const departmentTree = ref([])

// 智能体部门树相关变量
const showAgentDeptTree = ref(false)
const agentDeptSearchText = ref('')
const agentDeptTreeRef = ref(null)

// 智能体部门树配置
const agentDeptTreeProps = {
  children: 'children',
  label: 'dept_name'
}

// 配置文本（用于JSON编辑）
const configText = ref('')

// 配置视图模式：json 或 form
const configViewMode = ref('json')
const configFormItems = ref([])

// 表单验证规则
const agentFormRules = {
  name: [
    { required: true, message: '请输入智能体名称', trigger: 'blur' },
    { min: 2, max: 64, message: '名称长度在 2 到 64 个字符', trigger: 'blur' }
  ],
  agent_type: [
    { required: true, message: '请选择智能体类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  category: [
    { max: 64, message: '分类长度不能超过 64 个字符', trigger: 'blur' }
  ],
  avatar: [
    { max: 500, message: '图标URL长度不能超过 255 个字符', trigger: 'blur' }
  ],
  version: [
    { max: 16, message: '版本号长度不能超过 16 个字符', trigger: 'blur' }
  ],
  config: [
    { validator: (rule, value, callback) => {
      if (configText.value.trim() && !validateJsonConfig()) {
        callback(new Error('请输入有效的JSON格式'));
      } else {
        callback();
      }
    }, trigger: 'blur' }
  ]
}

// 计算属性
const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    inactive: 'warning',
    deleted: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusLabel = (status) => {
  const statusMap = {
    active: '活跃',
    inactive: '非活跃',
    deleted: '已删除'
  }
  return statusMap[status] || status
}

// 使用正确的 formatDateTime 函数替换 formatDate
const formatDate = (dateStr) => {
  return formatDateTime(dateStr, true)
}

// 上传相关方法
const handleAvatarSuccess = (response, uploadFile) => {
  if (response && response.code === 200 && response.data) {
    agentForm.avatar = response.data.url
    ElMessage.success('图标上传成功')
  } else {
    ElMessage.error('图标上传失败')
  }
}

const handleAvatarError = (error) => {
  console.error('上传图标失败:', error)
  ElMessage.error('图标上传失败')
}

const beforeAvatarUpload = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const removeAvatar = () => {
  agentForm.avatar = ''
}

// 方法
const loadAgents = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    // 使用真实API
    const response = await getAgentList(params)
    console.log('API响应数据:', response)
    if (response.data) {
      agents.value = response.data.items || []
      total.value = response.data.total || 0
      
      // 调试：检查每个智能体的avatar字段
      agents.value.forEach((agent, index) => {
        console.log(`智能体 ${index + 1}:`, {
          id: agent.id,
          name: agent.name,
          avatar: agent.avatar,
          avatarType: typeof agent.avatar,
          avatarLength: agent.avatar ? agent.avatar.length : 0
        })
      })
    }
  } catch (error) {
    console.error('加载智能体列表失败:', error)
    ElMessage.error(error.response?.data?.message || '加载智能体列表失败')
    agents.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 加载智能体类型
const loadAgentTypes = async () => {
  try {
    // 使用真实API或默认值
    agentTypes.value = ['内嵌型', '外链型']
  } catch (error) {
    console.error('加载智能体类型失败:', error)
    ElMessage.error('加载智能体类型失败')
    agentTypes.value = []
  }
}

// 加载智能体状态
const loadAgentStatuses = async () => {
  try {
    // 使用真实API或默认值
    agentStatuses.value = ['active', 'inactive', 'deleted']
  } catch (error) {
    console.error('加载智能体状态失败:', error)
    ElMessage.error('加载智能体状态失败')
    agentStatuses.value = []
  }
}

// 加载智能体分类
const loadAgentCategories = async () => {
  try {
    // 使用真实API或默认值
    agentCategories.value = ['客服助手', '技术支持', '营销推广', '内容创作', '数据处理', '教育培训']
  } catch (error) {
    console.error('加载智能体分类失败:', error)
    ElMessage.error('加载智能体分类失败')
    agentCategories.value = []
  }
}

// 加载部门数据
const loadDepartments = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.data) {
      // 保存部门树数据
      departmentTree.value = response.data.items || response.data
      // 将树形数据转换为扁平的选项数组
      departmentOptions.value = flattenDepartmentTree(departmentTree.value)
    }
  } catch (error) {
    console.error('加载部门数据失败:', error)
    ElMessage.error('加载部门数据失败')
  }
}

// 将部门树扁平化为选项数组
const flattenDepartmentTree = (tree, prefix = '') => {
  let options = []
  tree.forEach(dept => {
    const label = prefix ? `${prefix} / ${dept.dept_name || dept.name}` : (dept.dept_name || dept.name)
    options.push({
      value: dept.dept_id || dept.id,
      label: label
    })
    
    if (dept.children && dept.children.length > 0) {
      options = options.concat(flattenDepartmentTree(dept.children, label))
    }
  })
  return options
}

// 智能体部门树相关方法
// 过滤部门树节点
const filterAgentDeptNode = (value, data) => {
  if (!value) return true
  return (data.dept_name || data.name).toLowerCase().includes(value.toLowerCase())
}

// 过滤部门树
const filterAgentDeptTree = (val) => {
  agentDeptTreeRef.value?.filter(val)
}

// 点击部门树节点
const handleAgentDeptNodeClick = (data) => {
  agentForm.department_id = data.dept_id || data.id
  agentForm.department_path = buildAgentDepartmentPath(data, departmentTree.value)
  showAgentDeptTree.value = false
}

// 清除部门选择
const clearAgentDepartmentSelection = (event) => {
  if (event) {
    event.stopPropagation()
  }
  agentForm.department_id = ''
  agentForm.department_path = ''
  if (agentDeptTreeRef.value) {
    agentDeptTreeRef.value.setCurrentKey(null)
  }
}

// 构建部门的完整路径
const buildAgentDepartmentPath = (dept, deptTree) => {
  if (!dept) return ''
  
  const pathParts = []
  pathParts.push(dept.dept_name || dept.name) // 当前部门名称
  
  // 尝试查找父级部门并构建完整路径
  let parentId = dept.parent_id
  while (parentId) {
    const parent = findDepartmentById(parentId, deptTree)
    if (parent) {
      pathParts.unshift(parent.dept_name || parent.name) // 添加到路径开头
      parentId = parent.parent_id
    } else {
      break
    }
  }
  
  // 用斜杠连接
  return pathParts.join('/')
}

// 查找指定ID的部门
const findDepartmentById = (deptId, tree) => {
  for (const dept of tree) {
    if ((dept.dept_id || dept.id) === deptId) {
      return dept
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDepartmentById(deptId, dept.children)
      if (found) return found
    }
  }
  return null
}

// 监听点击事件，点击外部关闭树形选择器
const handleAgentClickOutside = (event) => {
  if (showAgentDeptTree.value) {
    const deptSelector = document.querySelector('.agent-dept-selector')
    if (deptSelector && !deptSelector.contains(event.target)) {
      showAgentDeptTree.value = false
    }
  }
}

// 添加防抖处理搜索
const handleSearch = debounce(() => {
  pagination.page = 1
  loadAgents()
}, 300)

const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  loadAgents()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadAgents()
}

// 查看详情方法
const viewAgentDetail = (agent) => {
  currentAgent.value = agent
  showDetailDialog.value = true
}

const handleCommand = (command) => {
  const [action, id] = command.split('-')
  const agentId = parseInt(id)
  
  if (action === 'edit') {
    editAgent(agentId)
  } else if (action === 'copy') {
    copyAgentHandler(agentId)
  } else if (action === 'delete') {
    confirmDelete(agentId)
  } else if (action === 'hard') {
    confirmHardDelete(agentId)
  }
}

// 复制智能体
const copyAgentHandler = async (agentId) => {
  try {
    const agent = agents.value.find(a => a.id === agentId)
    if (!agent) {
      ElMessage.error('找不到该智能体')
      return
    }
    
    const copyData = {
      name: `${agent.name} - 副本`,
      description: agent.description,
      avatar: agent.avatar,
      category: agent.category,
      agent_type: agent.agent_type,
      status: 'inactive', // 复制的智能体默认为非活跃状态
      department_id: agent.department_id,
      version: '1.0.0', // 重置版本号
      config: agent.config
    }
    
    await copyAgent(agentId, copyData)
    ElMessage.success('复制成功')
    loadAgents()
  } catch (error) {
    console.error('复制智能体失败:', error)
    ElMessage.error(error.response?.data?.message || '复制失败')
  }
}

// 确认硬删除
const confirmHardDelete = async (agentId) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该智能体，无法恢复，是否继续？',
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    loading.value = true
    await hardDeleteAgent(agentId)
    ElMessage.success('永久删除成功')
    loadAgents()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('永久删除智能体失败:', error)
      ElMessage.error(error.response?.data?.message || '永久删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 编辑智能体方法
const editAgent = (agentId) => {
  const agent = agents.value.find(a => a.id === agentId)
  if (agent) {
    editingAgent.value = agent
    Object.assign(agentForm, {
      name: agent.name,
      description: agent.description || '',
      avatar: agent.avatar || '',
      category: agent.category || '',
      agent_type: agent.agent_type,
      status: agent.status,
      department_id: agent.department_id || '',
      version: agent.version || '1.0.0',
      config: agent.config
    })
    
    // 设置部门路径
    if (agent.department_id && departmentTree.value.length > 0) {
      const dept = findDepartmentById(agent.department_id, departmentTree.value)
      if (dept) {
        agentForm.department_path = buildAgentDepartmentPath(dept, departmentTree.value)
      }
    } else {
      agentForm.department_path = ''
    }
    
    configText.value = agent.config ? JSON.stringify(agent.config, null, 2) : ''
    // 如果当前是表单视图模式，则更新表单配置项
    if (configViewMode.value === 'form') {
      updateFormFromConfig()
    }
    showCreateDialog.value = true
    showDetailDialog.value = false
  } else {
    ElMessage.error('找不到该智能体')
  }
}

// 确认删除方法
const confirmDelete = async (agentId) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该智能体，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    await deleteAgent(agentId)
    ElMessage.success('删除成功')
    loadAgents()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除智能体失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  if (!agentFormRef.value) return
  
  await agentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 处理配置JSON
        let config = null
        if (configText.value.trim()) {
          try {
            config = JSON.parse(configText.value)
          } catch (e) {
            ElMessage.error('配置格式不正确，请输入有效的JSON')
            submitting.value = false
            return
          }
        }
        
        const formData = {
          ...agentForm,
          config
        }
        
        if (editingAgent.value) {
          await updateAgent(editingAgent.value.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createAgent(formData)
          ElMessage.success('创建成功')
        }
        
        resetForm()
        loadAgents()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      } finally {
        submitting.value = false
      }
    } else {
      // 表单验证失败
      ElMessage.warning('请正确填写表单')
      return false
    }
  })
}

// 重置表单方法
const resetForm = () => {
  showCreateDialog.value = false
  editingAgent.value = null
  configViewMode.value = 'json' // 重置为JSON视图模式
  configFormItems.value = [] // 清空表单配置项
  showAgentDeptTree.value = false // 关闭部门树
  agentDeptSearchText.value = '' // 清空搜索文本
  
  if (agentFormRef.value) {
    agentFormRef.value.resetFields()
  }
  if (agentDeptTreeRef.value) {
    agentDeptTreeRef.value.setCurrentKey(null)
  }
  
  nextTick(() => {
    Object.assign(agentForm, {
      name: '',
      description: '',
      avatar: '',
      category: '',
      agent_type: '',
      status: 'active',
      department_id: '',
      department_path: '',
      version: '1.0.0',
      config: null
    })
    configText.value = ''
  })
}

// 快速搜索功能
const quickSearch = async (keyword) => {
  if (!keyword.trim()) {
    return
  }
  
  try {
    const response = await searchAgents(keyword, 10)
    if (response.data) {
      agents.value = response.data
      total.value = response.data.length
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

// 生命周期
onMounted(() => {
  loadAgents()
  loadAgentTypes()
  loadAgentCategories()
  loadAgentStatuses()
  loadDepartments()
  
  // 设置上传请求头，添加认证信息
  const token = localStorage.getItem('token')
  if (token) {
    uploadHeaders.value = {
      Authorization: `Bearer ${token}`
    }
  }
})

// 添加组件卸载时清理
onBeforeUnmount(() => {
  // 清理可能的副作用
})

// 添加JSON验证方法
const validateJsonConfig = () => {
  if (!configText.value.trim()) return true
  try {
    JSON.parse(configText.value)
    return true
  } catch (e) {
    return false
  }
}

// 从表单更新JSON配置
const updateConfigFromForm = () => {
  const config = {}
  configFormItems.value.forEach(item => {
    if (item.key.trim()) {
      try {
        // 尝试将值转换为适当的类型（数字、布尔值等）
        let value = item.value
        if (value === 'true') value = true
        else if (value === 'false') value = false
        else if (!isNaN(Number(value)) && value.trim() !== '') value = Number(value)
        config[item.key] = value
      } catch (e) {
        config[item.key] = item.value
      }
    }
  })
  configText.value = JSON.stringify(config, null, 2)
}

// 从JSON更新表单配置
const updateFormFromConfig = () => {
  configFormItems.value = []
  try {
    if (configText.value.trim()) {
      const config = JSON.parse(configText.value)
      Object.entries(config).forEach(([key, value]) => {
        configFormItems.value.push({
          key,
          value: typeof value === 'object' ? JSON.stringify(value) : String(value)
        })
      })
    }
    // 如果配置为空，添加一个空行方便用户输入
    if (configFormItems.value.length === 0) {
      configFormItems.value.push({ key: '', value: '' })
    }
  } catch (e) {
    console.error('解析JSON失败:', e)
    // 解析失败时，添加一个空行方便用户输入
    configFormItems.value.push({ key: '', value: '' })
  }
}

// 添加配置项
const addConfigItem = () => {
  configFormItems.value.push({ key: '', value: '' })
}

// 移除配置项
const removeConfigItem = (index) => {
  configFormItems.value.splice(index, 1)
  updateConfigFromForm()
}

// 监听配置视图模式变化
watch(configViewMode, (newMode) => {
  if (newMode === 'form') {
    updateFormFromConfig()
  } else {
    // 从表单模式切换到JSON模式时，确保JSON是最新的
    updateConfigFromForm()
  }
  
  // 添加一个延迟，确保DOM更新后再聚焦
  nextTick(() => {
    // 确保视觉上的一致性
    if (configFormItems.value.length === 0 && newMode === 'form') {
      addConfigItem()
    }
  })
})

// 监听configText变化，当在JSON模式下直接编辑时更新表单
watch(configText, (newValue) => {
  if (configViewMode.value === 'json' && validateJsonConfig()) {
    // 仅当JSON有效时才更新表单
    updateFormFromConfig()
  }
}, { debounce: 500 })

// 根据智能体类型返回对应的图标
const getAgentIcon = (agent_type) => {
  const iconMap = {
    '内嵌型': 'ChatDotRound',
    '外链型': 'Link',
    '对话型': 'ChatDotRound',
    '知识库': 'Collection',
    '流程型': 'Connection',
    '数据分析': 'DataAnalysis',
    '创意助手': 'MagicStick',
    '代码助手': 'Cpu'
  }
  return iconMap[agent_type] || 'ChatDotRound'
}

// 处理图片加载错误
const handleImageError = (event, agent) => {
  console.warn(`智能体 ${agent.name} 的图标加载失败:`, agent.avatar)
  
  // 隐藏图片，让底层的默认图标显示出来
  event.target.style.display = 'none'
}

// 处理图片加载成功
const handleImageLoad = (event) => {
  console.log('图标加载成功:', event.target.src)
  
  // 图片加载成功时，图片会自动覆盖默认图标，无需额外操作
}

// 获取安全的图标URL
const getSafeAvatarUrl = (agent) => {
  if (!agent.avatar) return null

  // 1. 以 http(s):// 开头的外链，直接返回
  if (/^https?:\/\//.test(agent.avatar)) {
    return agent.avatar
  }

  // 2. 以 /api/ 开头，直接返回
  if (agent.avatar.startsWith('/api/')) {
    return agent.avatar
  }

  // 3. MinIO 存储的图片，转换为 API 路径
  if (agent.avatar.startsWith('avatars/')) {
    return `/api/v1/files/${agent.avatar}`
  }

  // 4. 其他情况，直接返回原始值
  return agent.avatar
}

</script>

<style lang="scss" scoped>
.agents-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 140px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 24px;
      font-weight: 600;
      background: linear-gradient(to right, #409eff, #67c23a);
      -webkit-background-clip: text;
      color: transparent;
    }

    .page-description {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }
}

.search-bar {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.agents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.agent-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #e4e7ed;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background: linear-gradient(to right, #409eff, #67c23a);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    border-color: #c6e2ff;
    
    &::before {
      opacity: 1;
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;

    .agent-info {
      display: flex;
      align-items: center;
      flex: 1;

      .agent-avatar {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        background: linear-gradient(135deg, #409eff, #67c23a);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        margin-right: 12px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        position: relative;

        .default-icon {
          display: flex; // 始终显示作为背景
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          z-index: 1; // 在底层
        }

        .avatar-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 12px;
          position: absolute;
          top: 0;
          left: 0;
          z-index: 2; // 在上层，覆盖默认图标
          background: white;
        }
      }

      .agent-basic {
        flex: 1;

        .agent-name {
          margin: 0 0 4px 0;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          line-height: 1.2;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .agent-type {
          font-size: 12px;
          color: #409eff;
          background: #ecf5ff;
          padding: 2px 8px;
          border-radius: 4px;
          text-transform: uppercase;
          font-weight: 500;
          display: inline-block;
          margin-right: 8px;
        }

        .agent-category {
          font-size: 12px;
          color: #67c23a;
          background: #f0f9ff;
          padding: 2px 8px;
          border-radius: 4px;
          font-weight: 500;
          display: inline-block;
        }
      }
    }

    .card-actions {
      opacity: 0;
      transition: opacity 0.2s ease;
    }
  }

  &:hover .card-actions {
    opacity: 1;
  }

  .card-content {
    margin-bottom: 16px;

    .agent-description {
      margin: 0 0 16px 0;
      color: #606266;
      font-size: 14px;
      line-height: 1.6;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      min-height: 42px;
    }

    .agent-meta {
      display: flex;
      flex-direction: column;
      gap: 8px;

      .meta-item {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #909399;

        .el-icon {
          margin-right: 6px;
          font-size: 14px;
          color: #67c23a;
        }
      }
    }
  }

  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid #f0f2f5;
    
    .model-info {
      font-size: 12px;
      color: #909399;
      background: #f5f7fa;
      padding: 2px 8px;
      border-radius: 4px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.agent-detail {
  .json-config {
    background: #f5f7fa;
    padding: 12px;
    border-radius: 4px;
    font-family: monospace;
    max-height: 300px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-all;
    margin: 0;
  }
}

.config-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
  width: 100%;
}

.config-tabs {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
  
  :deep(.el-radio-group) {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
  
  :deep(.el-radio-button__inner) {
    padding: 8px 20px;
    font-weight: 500;
  }
}

.config-form-mode {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #f8f9fa;
  max-height: 300px;
  overflow-y: auto;
  width: 100%;
  
  :deep(.el-textarea__inner) {
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    width: 100%;
    box-sizing: border-box;
  }
  
  .json-editor-container {
    padding: 5px;
    width: 100%;
  }
}

.config-form-item {
  margin-bottom: 10px;
  width: 100%;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .el-row {
    width: 100%;
  }
}

.config-form-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-start;
}

/* 头像上传样式 */
.avatar-uploader {
  width: 100%;
  
  .avatar-preview {
    position: relative;
    width: 100px;
    height: 100px;
    margin-bottom: 10px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .avatar-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .avatar-actions {
      position: absolute;
      top: 5px;
      right: 5px;
      opacity: 0;
      transition: opacity 0.3s;
    }
    
    &:hover .avatar-actions {
      opacity: 1;
    }
  }
  
  .avatar-upload {
    margin-bottom: 10px;
    
    .el-upload__tip {
      margin-top: 5px;
      font-size: 12px;
      color: #909399;
    }
  }
  
  .avatar-input {
    margin-top: 10px;
  }
}

// 添加JSON错误样式
:deep(.is-error) {
  .el-textarea__inner {
    border-color: var(--el-color-danger);
  }
}

/* 智能体部门选择器样式 */
.agent-dept-selector {
  position: relative;
  width: 100%;
  
  .el-input {
    width: 100%;
  }
  
  .agent-tree-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background-color: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 100;
    margin-top: 5px;
    width: 100%;
    
    .tree-search {
      padding: 8px;
      border-bottom: 1px solid #ebeef5;
      background-color: #f5f7fa;
    }
    
    .agent-tree-container {
      background-color: #fff;
      
      :deep(.el-tree) {
        padding: 5px;
        
        .el-tree-node__content {
          height: 24px; /* Compact height */
          padding-left: 8px !important;
          
          &:hover {
            background-color: #f5f7fa;
          }
        }
        
        .is-current > .el-tree-node__content {
          background-color: #ecf5ff;
          color: #409EFF;
        }
        
        /* Reduce spacing between nodes */
        .el-tree-node {
          padding-bottom: 0;
        }
        
        /* Adjust the expand arrow position */
        .el-tree-node__expand-icon {
          padding: 4px;
        }
        
        /* Smaller font size */
        .el-tree-node__label {
          font-size: 13px;
        }
        
        /* Adjust indentation for better hierarchy visualization */
        .el-tree-node__children {
          padding-left: 16px;
        }
      }
      
      .selected-dept {
        color: #409EFF;
        font-weight: 500;
        font-size: 13px; /* Smaller font size */
      }
      
      .compact-tree-node {
        display: flex;
        align-items: center;
        font-size: 13px;
        line-height: 1.2;
        padding: 2px 0;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .agents-grid {
    grid-template-columns: 1fr;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .search-bar {
    .el-row {
      flex-direction: column;
      gap: 12px;
    }
  }
}
</style>
